package com.xxs.utils.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.xxs.common.Const;

@SuppressWarnings("unchecked")
public class XmlDom4jUtils {
    //获取Document对象
	public static Document getDocument(String xmlPath){  
		SAXReader reader = new SAXReader();  
		Document document = null;
		try {
			document = reader.read(new File(xmlPath));
			if(document == null){
	        	//创建文件
	        	Element root = DocumentHelper.createElement("xxs");  
	            Document doc = DocumentHelper.createDocument(root); 
	        	saveDocumentToFile(xmlPath, doc);
	        }
		}catch (Exception e) {
			e.printStackTrace();
		}  
		return document;
	} 
	//获取目标节点
    public static Element getRootElement(String xmlPath){  
	    return getDocument(xmlPath).getRootElement();
    } 
	//获取目标节点
    public static List<Element> getElements(String modelName,String name){  
        Document document = getDocument(modelName);
        Element element = document.getRootElement();  
	    if(name!=null){
	        return element.elements(name);
	    }else{
	    	return element.elements();
	    }
    } 
    //document写入新的文件  
    public static void saveDocumentToFile(String xmlPath,Document document)throws Exception{
        //输出格式  
        OutputFormat format = OutputFormat.createPrettyPrint();  
        //设置编码  
        format.setEncoding("UTF-8");  
        //XMLWriter 指定输出文件以及格式  
        XMLWriter writer = new XMLWriter(new FileOutputStream(xmlPath), format);  
        //写入新文件  
        writer.write(document);  
        writer.flush();  
        writer.close();  
    }  
    //获取模型默认字段
    public static List<Models> getDefModels(){ 
    	String xmlPath = Const.XML_PREFIX+Const.SYSTEM_TABLES_PATH+Const.XML_SUFFIX;
    	List<Models> modelLists = new ArrayList<Models>();
    	Document document = getDocument(xmlPath);
		//获取根节点元素对象  
		List<Element> listElements = document.selectNodes("/systems/field");
		//首先获取当前节点的所有属性节点  
		for (int i = 0; i < listElements.size(); i++) {
			List<Attribute> attributes  = listElements.get(i).attributes();
			for (int j = 0; j < attributes.size(); j++) {
				String text = attributes.get(j).getText();
				String name = attributes.get(j).getName();
				System.out.println("name:"+name+"||text:"+text);
			}
		}  
    	return modelLists;
    }
    
    /**
     * modelName 文件地址
     * modelName 模型名称
     * attrName 搜索条件
     * attrValue 搜索条件值
     * parameterName 输出的参数名称
     */
    public static String getParaValueByAttrAndValue(String xmlPath,String modelName,String attrName,String attrValue,String parameterName){ 
    	return getSingleElementsByAttrAndValue(xmlPath, modelName, attrName, attrValue).attributeValue(parameterName);
    }
    /**
     * modelName 文件地址
     * modelName 模型名称
     * attrName 搜索条件
     * attrValue 搜索条件值
     */
    public static List<Element> getElementsByAttrAndValue(String xmlPath,String modelName,String attrName,String attrValue){ 
    	Document document = getDocument(xmlPath);
    	return document.selectNodes("//"+modelName+"[@"+attrName+"='"+attrValue+"']");
    }
    /**
     * modelName 文件地址
     * modelName 模型名称
     * attrName 搜索条件
     * attrValue 搜索条件值
     */
    public static Element getSingleElementsByAttrAndValue(String xmlPath,String modelName,String attrName,String attrValue){ 
    	List<Element> list = getElementsByAttrAndValue(xmlPath, modelName, attrName, attrValue);
		return list!=null && list.size()>0 ? list.get(0):null;
    }
    //获取表结构的fields字段集
    public static List<Fields> getFieldsByAttrAndValue(String xmlPath,String modelName,String attrName,String attrValue){  
    	return getFields(getSingleElementsByAttrAndValue(xmlPath, modelName, attrName, attrValue));
    }  
    //获取表结构的fields字段集
    public static List<Fields> getFields(String xmlPath,String modelName){  
		Element rootelement = getRootElement(xmlPath);  
		if(modelName!=null){
			rootelement = rootelement.element(modelName);
		}
		return getFields(rootelement);  
    }  
  //获取表结构的fields字段集
    public static List<Fields> getFields(Element element){  
    	List<Fields> modelLists = new ArrayList<Fields>();
	    Iterator<Element> iterator = element.elementIterator();  
	    while(iterator.hasNext()){  
	        Element e = iterator.next();  
		    Fields fields = new Fields();
		    fields.setName(e.getName());
		    fields.setLabel(e.attribute("label").getText());
		    fields.setType(e.attribute("type").getText());
		    fields.setList(e.attribute("list").getText());
		    fields.setEdit(e.attribute("edit").getText());
		    fields.setQuery(e.attribute("query").getText());
		    modelLists.add(fields);
	    }  
		return modelLists;
    }  
	//遍历当前节点下的所有节点  
    public void loopElement(Element element){  
        System.out.println("当前节点的名称：" + element.getName());  
        //首先获取当前节点的所有属性节点  
        List<Attribute> list = element.attributes();  
        //遍历属性节点  
        for(Attribute attribute : list){  
            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());  
        }  
        //如果当前节点内容不为空，则输出  
        if(!(element.getTextTrim().equals(""))){  
             System.out.println( element.getName() + "：" + element.getText());    
        }  
        //同时迭代当前节点下面的所有子节点  
        //使用递归  
        Iterator<Element> iterator = element.elementIterator();  
        while(iterator.hasNext()){  
            Element e = iterator.next();  
            loopElement(e);  
        }  
    } 
}
